package com.tbvtc.agriculturalcreditchainserver2025.utils;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbvtc.agriculturalcreditchainserver2025.entity.UserAddress;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CartMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.IUserAddressService;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartAddressVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartSelectPhoneAndGoodByUserId;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.addressItem;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Component
@RequiredArgsConstructor
public class CartSelectUtils {
    @Autowired
    private final CartMapper cartMapper;
    @Resource
    private IUserAddressService userAddressService;
    public  void selectPhoneAndGoodByUserId(List<CartSelectPhoneAndGoodByUserId> list, Integer userId, Integer state){
        //获取名字
        cartMapper.selectAddressResName(userId);
        //添加到发货表状态为已支付
        List<addressItem> addressVos = cartMapper.selectAddressByUserId(userId);
        Snowflake snowflake = new Snowflake(1L, 1L); // workerId, datacenterId
        long id1 = snowflake.nextId();
        long id2 = snowflake.nextId();
        String address = "";
        for (addressItem addressVo : addressVos) {
            if ("1".equals(addressVo.getIsDefault())) {
                address = addressVo.getAddress();
            }
        }
            //购物车里的订单为一样的订单编号,而且一个商铺一个订单编号
            for (CartSelectPhoneAndGoodByUserId cartSelectPhoneAndGoodByUserId : list) {
                if (cartSelectPhoneAndGoodByUserId.getIsMature() == 1) {
                    cartSelectPhoneAndGoodByUserId.setOrderId(String.valueOf(id1));
                } else {
                    cartSelectPhoneAndGoodByUserId.setOrderId(String.valueOf(id2));
                }
                cartSelectPhoneAndGoodByUserId.setTime(LocalDateTime.now()); // 设置时间
                cartSelectPhoneAndGoodByUserId.setUserId(userId); // 设置用户ID
                cartSelectPhoneAndGoodByUserId.setAddress(address); // 设置地址
                cartSelectPhoneAndGoodByUserId.setUsername( userAddressService.getOne(new LambdaQueryWrapper<UserAddress>()
                        .eq(UserAddress::getUserId,userId)
                        .eq(UserAddress::getIsDefault, 1)
                ).getReceiverName());// 设置用户名
                cartSelectPhoneAndGoodByUserId.setState(state); // 设置状态为已支付
                cartMapper.addOrder(cartSelectPhoneAndGoodByUserId); // 添加到发货表
            }


    }
}
